import React from 'react';
import { Button } from 'antd-mobile';

class SendSmsCode extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      disabled: false,
      text: '获取注册验证码',
      remainSec: 60,
    };
  }

  componentWillUnmount() {
    clearInterval(this.sta);
  }

  onGetCode() {
    const status = this.props.onSendSmsCode();
    if (status) {
      this.setState({
        disabled: true,
        text: '60秒',
        remainSec: 60,
      });
      this.timer = setInterval(
        () => { // Correct
          if (this.state.remainSec === 0) {
            this.setState({
              disabled: false,
              text: '获取验证码',
            });
            clearInterval(this.timer);
          } else {
            this.setState(prevState => ({
              remainSec: prevState.remainSec - 1,
              text: `${prevState.remainSec - 1}秒`,
            }));
          }
        },
        1000,
      );
    }
  }

  render() {
    return (
      <Button type="ghost" onClick={this.onGetCode.bind(this)} disabled={this.state.disabled} size="small" inline>{this.state.text}</Button>
    );
  }
}

export default SendSmsCode;
